import { createRouter, createWebHashHistory } from 'vue-router'

import LoginView from '@/views/LoginView.vue'
import HomeView from '@/views/HomeView.vue'

import ProjectManagement from '@/views/ProjectManagement.vue'
import DocumentManagement from '@/views/DocumentManagement.vue'
import DocumentDetails from '@/views/DocumentDetails.vue'
import KnowledgeGraphView from '@/views/demension/KnowledgeGraphView.vue'

const routes = [
  {
    path: '/',
    name: 'login',
    component: LoginView
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    children: [
      {
        path: '/home/project',
        name: 'ProjectManagement',
        component: ProjectManagement
      }
    ]
  },
  {
    path: '/DocumentManagement/:projectId/:projectName/:projectDescription',
    name: 'DocumentManagement',
    component: DocumentManagement
  },
  {
    path: '/DocumentDetails/:documentId/:projectId/:projectName/:projectDescription',
    name: 'DocumentDetails',
    component: DocumentDetails
  },
  {
    path: '/KnowledgeGraphView/:documentId',
    name: 'KnowledgeGraphView',
    component: KnowledgeGraphView
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    const token = localStorage.getItem('token')
    if (!token) {
      // 需要认证但没有token，重定向到登录页
      next({ name: 'login' })
    } else {
      // 有token，检查路由参数
      if (to.name === 'DocumentManagement' && !to.params) {
        next({ name: 'Home' })
      } else if (to.name === 'DocumentDetails' && !to.params) {
        next({ name: 'Home' })
      } else {
        next()
      }
    }
  } else {
    // 不需要认证的路由直接放行
    next()
  }
})

export default router
